<?php

namespace app\api\controller;

use app\api\service\MemorderService;
use app\api\service\OrderService;
use app\common\controller\Api;
use app\common\model\Addresses;
use app\common\model\Area;
use app\common\model\Cart;
use app\common\model\Goodorder;
use app\common\model\member\order\Items;
use app\common\model\member\product\Specs;
use app\common\model\Occupants;
use app\common\model\Ordersessions;
use app\common\model\RefundReasons;
use app\common\model\Rooms;
use app\manystore\model\Categories;
use app\manystore\model\ManystoreShop;
use app\manystore\model\Spece;
use think\Cache;
use think\Db;

/**
 * 点单商品
 */
class Memorder extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
    }




    /*
     * 会员商城下单
     */

    public function add_mem_order(){

        if (!$method= input('method')) {
            $this->error(__('请选择配送方式'));
        }

        $data = input('post.');
        $cacheKey = 'submit_' . md5(serialize($data));
        // 检查缓存中是否存在该键名
        if (Cache::has($cacheKey)) {
            $this->error(__('您点的太快了'));
        }
        Cache::set($cacheKey, true, 3);

        if($method=='delivery'){
            if (!$adrid= input('adrid')) {
                $this->error(__('请选择地址'));
            }
            $address=Addresses::where('id',$adrid)->field('id,address,phone,name,is_default,sex,(select name from fa_area where fa_area.id=province_id) province,(select name from fa_area where fa_area.id=city_id) city,(select name from fa_area where fa_area.id=district_id) district')->find();
        }

        $user=\app\common\model\User::where('id',$this->auth->id)->find();
        $delivery_fee=0;//快递费
        $order = \app\common\model\member\Order::create([
            'user_id' => $this->auth->id,
            'method' => input('method'),
            'order_no' => order_no(),
            'address' => $method == 'delivery' ?$address['province'].$address['city'].$address['district']. $address['address'] : '',
            'linkman' => $method == 'delivery' ? $address['name'] : '',
            'linkphone' => $method == 'delivery' ? $address['phone'] : '',
            'remarks'=> input('remarks'),
            'expire_pay_time'=>time() + 15 * 60,
            'delivery_fee'=>$delivery_fee,
        ]);

        db::startTrans();
        //1是购物车
        if(input('cart_id')!=null){
            $array=Cart::where('user_id',$this->auth->id)->where('id','in',input('cart_id'))->select();
            Cart::where('user_id',$this->auth->id)->where('id','in',input('cart_id'))->delete();
        }else{
            //2是立即结算
            $array[]=['product_id'=>input('product_id'),'spec_id'=>input('spec_id'),'num'=>input('num')];
        }
        $sum=0;
        foreach ($array as $item){
            $Products=\app\common\model\member\Products::where('id',$item['product_id'])->find();
            //多规格
            $has_specs=0;
            $Spece='';
            if($item['spec_id']!=null&&$item['spec_id']!=''){
               $Spece= Specs::where('id',$item['spec_id'])->find();
               $has_specs=1;
            }
            $price=$Spece?$Spece['price']:$Products['price'];
            Items::create([
                'order_id'=>$order->id,
                'product_id'=>$item['product_id'],
                'num'=>$item['num'],
                'price'=>$price,
                'total'=>$price*$item['num'],
                'specs'=>$has_specs==1?$Spece['spec_name']:'常规',
                'specs_id'=>$has_specs==1?$Spece['id']:null,
                'goodimage'=>$Products['image'],
                'goodname'=>$Products['name'],
            ]);
            //商品总额
            $sum+=$price*$item['num'];
            //快递费
            if(input('method')=='delivery'){
                $delivery_fee+=$Products['postage']*$item['num'];
            }
            if($has_specs==0){
               $result= \app\common\model\member\Products::where('id',$item['product_id'])->where('stock','=',$Products['stock'])->setDec('stock',$item['num']);
            }else{
              $result=  Specs::where('id',$item['spec_id'])->where('stock','=',$Spece['stock'])->setDec('stock',$item['num']);
            }
            if($result==0){
                db::rollback();
                $this->error('商品库存不足');
            }
            Cart::where('id',$item['spec_id'])->delete();
        }
        $good_money=$sum;
        $sum+=$delivery_fee;

        $user_money=$user['money'];
        $leftmoeny = $sum - 0;//扣掉优惠券金额
        $balance_used = min($user_money, $leftmoeny); // 使用余额抵扣剩余金额
        $leftmoeny -= $balance_used; // 更新最后的剩余金额

        \app\common\model\member\Order::where('id',$order->id)->update(['paid'=>$leftmoeny,'balance'=>$balance_used,'amount'=>$sum,'good_amount'=>$good_money,'postage'=>$delivery_fee]);
        db::commit();
        if($leftmoeny==0){
            $server=new MemOrderService();
            $server->order_success($order->id);
            $this->success('请求成功', [
                'is_pay' => 0,
                 'id' => $order->id,
                'order_no' => $order->order_no,
            ]);
        }else{
            $this->success('请求成功', [
                'is_pay' => 1,
                'id' => $order->id,
                'order_no' => $order->order_no,
            ]);
        }

    }

    //订单支付
    public function Order_payment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $order_no = order_no();
        $result=\app\common\model\member\Order::where('id','=',$id)->where('pay_status','=',0)->update(['order_no'=>$order_no]);
        if($result===0){
            $this->error('当前订单已支付');
        }
        $payment = MemorderService::order_payment($id, $this->auth->id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }

    //订单列表
    public function order_list($type = null) {
        $query = \app\common\model\member\Order::where('user_id', $this->auth->id);

        // 如果 status 被提供且不为空，则添加条件
        if ($type != null&&$type != '') {
            $query->where('status', $type+1);
        }else{
            $query->where('status', '<>',0);
        }

        $query->where('pay_status', '=',1);
        // 分页并返回结果
        $list= $query->field('id,order_no,status')->order('id desc')->paginate(10);

        foreach ($list as $item){
            $total=0;
           $info= Items::where('order_id',$item['id'])->field('goodimage,goodname,num,total')->select();
            foreach ($info as $item1){
                $total+=$item1['total'];
            }
            $item->item=$info;
            $item->total=round($total,2);
            $item->count=count($info);
        }

        $this->success('请求成功',$list);
    }

    /*
     * 订单详情
     */
    public function order_info(){
        $info=\app\common\model\member\Order::where('id',input('id'))->field('id,method,status,address,remarks,order_no,cancel_time,pay_time,linkman,linkphone,delivery_fee,good_amount,amount,createtime,refund_time,refund_sh_status,refund_sh_cause,refund_sh_time,back_express_image,back_express_name,back_express_no,express_name,express_no,createtime,postage')->find();
        if($info){
            $item= Items::where('order_id',$info['id'])->field('goodimage,goodname,num,price,specs')->select();
            $info['item']=$item;
            $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);
            $info['pay_time'] = date('Y-m-d H:i:s', $info['pay_time']);
            if($info['status']==5){
                $info['back_info']=[
                    'refund_time'=>date('Y-m-d H:i:s', $info['refund_time']),
                    'refund_sh_status'=> $info['refund_sh_status'],
                     'refund_sh_cause'=> $info['refund_sh_cause'],
                      'refund_sh_time'=> date('Y-m-d H:i:s', $info['refund_sh_time']),
                ];
                if($info['back_express_name']!=null){
                    $info['back_express']=[
                        'back_express_image'=> $info['back_express_image']==""?[]:explode(',', $info['back_express_image']),
                        'back_express_name'=> $info['back_express_name'],
                        'back_express_no'=> $info['back_express_no'],
                    ];
                }else{
                    $info['back_express']=[];
                }

            }
            $info['postage']=round( $info['postage'],2);
            $info['good_amount']=round( $info['good_amount'],2);
        }
        $this->success('请求成功',$info);
    }

    /*
     * 取消订单
     */
    public function cancel_order(){
        $order=\app\common\model\member\Order::where('id',input('id'))->find();
        if(!$order){
            $this->error(__('订单不存在'));
        }
        if($order['status']!=1){
            $this->error(__('当前订单无法取消'));
        }
        \app\common\model\member\Order::where('id',input('id'))->update(['cancel_time'=>time(),'status'=>4]);
        $this->success('请求成功',[]);
    }

    /*
     * 确认收货
     */
    public function confirm_order(){
        $order=\app\common\model\member\Order::where('id',input('id'))->find();
        if(!$order){
            $this->error(__('订单不存在'));
        }
        if($order['status']!=2){
            $this->error(__('当前订单无法收货'));
        }
        \app\common\model\member\Order::where('id',input('id'))->update(['cancel_time'=>time(),'status'=>3]);
        $this->success('请求成功',[]);
    }

    //获取物流API
    public function express_info()
    {

        $order = \app\common\model\member\Order::where('id','=',input('id'))->find();
        if ($order['status'] !=2&&$order['status'] !=3&&$order['status'] !=5) {
            return fail('该订单暂未发货');
        }
        $express_name= $order['express_name'];
        $expressno=$order['express_no'];

        $express_company = db::table('fa_express_company')->where('express_name' ,'like', $express_name)->find();
        //参数设置
        $key = 'BHlZXckO8334';                        //客户授权key
        $customer = '8A0E592210113AAB4DAB0C2E47C56ADF';                   //查询公司编号
        $param = array (
            'com' => $express_company['express_code'],          //快递公司编码
            'num' => $expressno,   //快递单号
            'phone' => $order['linkphone'],                //手机号
            'from' => '',                 //出发地城市
            'to' =>  $order['address'],                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/maptrack.do';    //实时查询请求地址
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result);
        if (isset($data->status) && $data->status == 200) {
            $this->success('请求成功', $data);
        } else {
            $this->error($data->message);
        }



    }

    /*
     * 退款理由
     */
    public function refund_reasons(){
      $data=  RefundReasons::field('reason,id')->select();
        $this->success('请求成功',$data);
    }

    /*
     * 退货退款
     */
    public function refund(){
        $Order=\app\common\model\member\Order::where('id',input('id'))->find();
        if($Order['status']!=2){
            $this->error(__('当前订单无法退款'));
        }
        if($Order['refund_sh_status']==2){
            $this->error(__('当前订单已售后完成'));
        }
        \app\common\model\member\Order::where('id',input('id'))->update(['refund_reason_id'=>input('refund_reason_id'),'refund_reason'=>input('refund_reason'),'refund_image'=>input('refund_image'),'status'=>5,'refund_sh_status'=>1,'refund_time'=>time()]);
        $this->success('请求成功',[]);
    }

    /*
     * 撤销退款
     */
    public function cancel_refund(){
        $Order=\app\common\model\member\Order::where('id',input('id'))->find();
        if($Order['status']!=5){
            $this->error(__('当前订单无法撤销'));
        }
        if($Order['refund_sh_status']==2){
            $this->error(__('审核通过,无法撤销'));
        }
        \app\common\model\member\Order::where('id',input('id'))->update(['refund_reason_id'=>'','refund_reason'=>'','refund_image'=>'','status'=>2,'refund_sh_status'=>1,'refund_time'=>'']);
        $this->success('请求成功',[]);
    }

    /*
     * 退款填写物流
     */

    public function refund_express(){
        $Order=\app\common\model\member\Order::where('id',input('id'))->find();
        if($Order['refund_sh_status']==1){
            $this->error(__('后台正在审核，请通过后提交'));
        }

        if($Order['back_express_no']!=null&&$Order['back_express_no']!=''){
            $this->error(__('请勿重复提交'));
        }
        \app\common\model\member\Order::where('id',input('id'))->update(['back_express_name'=>input('express_name'),'back_express_no'=>input('express_no'),'back_express_image'=>input('express_image')]);
        $this->success('请求成功',[]);

    }

    /*
     * 快递公司
     */
    public function express(){
        $express_company = db::table('fa_express_company')->select();
        $this->success('请求成功',$express_company);
    }

    /*
     * 购物车下单商品列表
     */
    public function cart_info(){
       $Cart= Cart:: field('id,num,spec_id')->where('type',0)->where('cart.status',0)->where('cart.id','in',input('ids'))->with('memproduct')->select();
       $sum=0;
       $postage=0;
       foreach ($Cart as $item){
            $item->getRelation('memproduct')->visible(['id','price','image','name']);
            if($item['spec_id']!=null){
                $Specs= Specs::where('id','=',$item['spec_id'])->find();
                $item->Specs=$Specs['spec_name'];
                $item->memproduct->price=$Specs['price'];
            }
            $sum+= ($item->memproduct->price*$item->num);
            $postage+=$item->memproduct->postage;
        }
        return json(['msg'=>'请求成功','data'=>$Cart,'code'=>1,'money'=>round($sum,2),'postage'=>round($postage,2)]);

    }

    /*
* 修改购物车数量
*/
    public function save_cart()
    {
        // 获取输入参数
        $cartId = input('id');
        $num = input('num'); // 假设输入的新的数量

        // 查找购物车记录
        $cartItem = Cart::where('id', $cartId)
            ->find();

        // 检查购物车记录是否存在
        if (!$cartItem) {
            $this->error('购物车记录不存在');
        }

        // 更新购物车数量
        $cartItem->num = $num;
        $cartItem->save();

        // 如果数量为0，则删除该记录
        if ($num <= 0) {
            $cartItem->delete();
            $this->success('请求成功', '已删除购物车记录');
        }

        $this->success('请求成功', '购物车数量已更新');
    }

    /*
     * 删除购物车
     */
    public function del_cart(){
        Cart::where('id','in',input('ids'))->where('user_id',$this->auth->id)->delete();
        $this->success('请求成功', '删除成功');
    }

    /*
     * 寄回信息
     */
    public function back_info(){
       $info= Db::table('fa_back_info')->order('id desc')->find();
        $this->success('请求成功',$info);
    }
}
